<?php
Yii::import('application.common.HTTPClient');
//微信红包发送类
class WechatReward {
	const  SENDURL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack'; //红包 发送地址	 
	const FINDURL = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/gethbinfo';  //红包查询地址 
	const AMOUNT = 101 ;   //设置最大最小红包金额 单位(分)
	const TOTALNUM = 1 ; //设置红包发放总人数
	public  $params = array();
	private $key = null ; 
	private  $appId ; 
	private $mchId ; 
	private  $errorMessage = '';
	private static $instance = null;
	private $pem = array(); 
	
	
	public function __construct($appId, $key, $mchId,array $pem=array()){
		$this->appId = $appId ; 
		$this->mchId = $mchId  ; 
		$this->key = $key ; 
		$this->pem = $pem ; 
	}
	
	public static function getInstance($appId, $key, $mchId,array $pem=array()) {
		if (is_null(self::$instance)) {
			self::$instance = new self($appId, $key, $mchId,$pem);
		}
		self::$instance->errorMessage = '';
		return self::$instance;
	}
	
	private function checkPem(){ //检测证书是否存在
		$msg = new ResponseMessage(); 
                
		if(!file_exists($this->pem['cert'])){
                     $msg->addErrorMessage('cert证书文件不存在');
		}
		
		if(!file_exists($this->pem['cert_key'])){
                        $msg->addErrorMessage('cert_ke证书文件不存在');                       
		}
                
                if(!file_exists($this->pem['rootca'])){
                        $msg->addErrorMessage('rootca证书文件不存在');                       
		}                
		return $msg ; 
	} 
	
	private function makeSign($params){ //生成签名
		ksort($params);  //排序	
		$sign = '';
		foreach ($params as $k=>$v){ 
			if(trim($v)==''){				 //对值为空的键去除掉
				unset($params[$k]);
			}
                        else
                        {
                            $sign .=$k.'='.$v.'&' ;
                        }
		}
		
		$stringSign = $sign."key=".$this->key;
                 
		$params['sign'] = strtoupper(md5($stringSign));
                
		return   $params ; 
		
	}
	
	private function makeBillno(){ //生成商户订单号
		return $this->mchId.date("Ymd").time();
		 
	}
	 
	private function addParams(){  //添加相应的参数
                $data = array();
		$data['mch_id'] = $this->mchId ; 
		$data['wxappid'] = $this->appId ; 
		$data['nonce_str'] = uniqid();		
		$data['mch_billno'] = $this->makeBillno(); 
		$data['nick_name'] = $this->params['send_name'];
		$data['client_ip']= Net::getIp();
                $min=$this->params['min_value'];
                $max=$this->params['max_value'];
                $money = Utils::getRangeNumber($min,$max);
		$data['total_amount'] = $money;
		$data['min_value'] = $money;
		$data['max_value'] = $money; 
		$data['total_num'] = self::TOTALNUM ;
		$this->params = array_merge($this->params,$data);  
  		
	}
	
	public function sendAction($params){  //发送参数到URL 
                
		$error = $this->checkPem(); 
		if($error->hasError()){
			return $error ;
		}
                   
		$params_error = $this->checkParams($params) ;		
               
		if($params_error->hasError()){                        
			return $params_error ; 
		}else{
			$this->params = $params ; 
		}
		$this->addParams();		
		$this->params =  $this->makeSign($this->params);	
                
		$http = HTTPClient::getInstance();		 
		$xml = XML::arrayToXml($this->params);
                
               try{
                   
                    $res = XML::xmlToArray($http->post_ssl(self::SENDURL, $xml, $this->pem, $this->mchId));
                   
               }
               catch(Exception $exception){
                   print_r($exception->getMessage());
               }
                $msg = new ResponseMessage(); 
               
		if ($res['return_code'] == 'FAIL' || $res['result_code'] == 'FAIL') {
			$this->errorMessage = isset($res['err_code_des']) ? $res['err_code_des'] : $res['return_msg'];
			 
                        $msg->addErrorMessage($this->errorMessage);
                        return $msg;
		}
                
		$this->errorMessage = '';
                $result = array(); 
                $result['mch_billno'] = $this->params['mch_billno']; 
                $result['total_amount'] = $this->params['total_amount']; 
                $msg->setData($result);
		return $msg;
		
	}
	
	public function findAction($billno){  //查询红包
		$data['nonce_str'] = uniqid();
		$data['mch_billno'] = $billno ; 
		$data['mch_id'] = $this->mchId ; 
		$data['appid'] = $this->appId ; 
		$data['bill_type'] = 'MCHT';
		$params = $this->makeSign($data);
		 
                
		$http = HTTPClient::getInstance();
		$xml = XML::arrayToXml($params);
		$res = XML::xmlToArray($http->post_ssl(self::FINDURL, $xml, $this->pem, $this->mchId));
                 
		if ($res['return_code'] == 'FAIL' || $res['result_code'] == 'FAIL') {
			$this->errorMessage = isset($res['err_code_des']) ? $res['err_code_des'] : $res['return_msg'];
			print_r($res );
                        return false;
		}
		$this->errorMessage = '';
		return $res ;
	}
	
	public function getErrorMessage() {
		return $this->errorMessage;
	}
	
	
	private  function checkParams(array $arr){  //检查用户构造类时是否传入apikey 及发送红包时所需相关参数
		
		$error = array();
		if(!$this->mchId){
			$error[] = 'mch_id';		
		}
		if(!$this->key){
			$error[] = 'key';
		}
		if(!$this->appId){
			$error[] = 'wxappid';
		}		
		if(!isset($arr['send_name']) || $arr['send_name'] ==''){
			$error[] = 'send_name';			
		}
		if(!isset($arr['re_openid']) || $arr['re_openid'] ==''){
			$error[] = 're_openid';
		}

		if(!isset($arr['wishing']) || $arr['wishing'] ==''){
			$error[] = 'wishing';
		}	
		if(!isset($arr['act_name']) || $arr['act_name'] ==''){
			$error[] = 'act_name';
		}
		if(!isset($arr['remark']) || $arr['remark'] ==''){
			$error[] = 'remark';
		}
		$resMessage = new ResponseMessage();
                $errmsg = implode(',', $error);
                if(count($error))
                {
                    $resMessage->addErrorMessage($errmsg.'不能为空');
                }
		return $resMessage ; 
	}

	
	
}